package com.springboot.frame.starter.web.xss;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.springboot.frame.web.xss.XssFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jackson.JsonComponentModule;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.util.HtmlUtils;
import java.io.IOException;

/**
 * xss对spring-boot的集成
 *
 * @author TaoYu
 */
@Configuration
@EnableConfigurationProperties(XssProperties.class)
@ConditionalOnProperty("web.xss.enabled")
public class XssAutoConfiguration {

  private final XssProperties properties;

  @Autowired
  public XssAutoConfiguration(XssProperties properties, JsonComponentModule jsonComponentModule) {
    this.properties = properties;
    jsonComponentModule.addDeserializer(String.class, new JsonDeserializer<String>() {
      @Override
      public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return HtmlUtils.htmlEscape(jsonParser.getValueAsString());
      }
    });
  }

  @Bean
  public FilterRegistrationBean xssFilterRegistrationBean() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new XssFilter());
    Integer order = properties.getOrder();
    filterRegistrationBean.setOrder(order);
    return filterRegistrationBean;
  }

}
